//
//  ExtensionClass.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/8/20.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import Foundation
import UIKit
import YYModel

extension UIViewController {

    // MARK: 设置错误提示框
    public func showErrorAlert(title :String? = "网络请求失败",msg:String? = "") {
        var errorStr = title
        if msg != "" {
            errorStr = global_requestFailed
        }
        KMTool.setAlertView(title:errorStr, msg:msg, target: self, haveCancel: false, handler: nil)
    }
    
    //MARK: 判断页面是否显示
    public func isCurrentViewControllerVisible(viewcontroller:UIViewController) -> Bool {
        return viewcontroller.isViewLoaded && (viewcontroller.view.window != nil)
    }

}

// MARK: - NSObject
extension NSObject {
    class func setModel(with dict:[String:Any]) -> Self {
        return self.yy_model(with: dict) ?? self.init()
    }
}

extension UIColor {
    
    class func lightYellow() -> UIColor {
        
        return UIColor.init(red: 229.0/255, green: 217.0/255, blue: 184.0/255, alpha: 1)
    }
    
    class func drakYellow() -> UIColor {
        
        return UIColor.init(red: 252.0/255, green: 232.0/255, blue: 97.0/255, alpha: 1)
    }
    
    class func loanFeeColor() -> UIColor {
        
        return UIColor.init(red: 67.0/255, green: 149.0/255, blue: 213.0/255, alpha: 1)
    }
    
    class func applicationColor() -> UIColor {
        
        return UIColor.init(red: 245.0/255, green: 186.0/255, blue: 65.0/255, alpha: 1)
    }
    
    class func lenderColor() -> UIColor {
        
        return UIColor.setRGB(0xDE3437)
    }
    
    class func mortgageColor() -> UIColor {
        
        return UIColor.setRGB(0x008000)
    }
    
    class func lineColor() -> UIColor {
        
        return UIColor.lightGray.withAlphaComponent(0.2)
    }
    
    class func pinkColor() -> UIColor {
        
        return UIColor.init(red: 201.0/255, green: 88.0/255, blue: 80.0/255, alpha: 1)
    }
    
    class func tabBarColor() -> UIColor {
        
        return UIColor.init(red: 214.0/255, green: 45.0/255, blue: 31.0/255, alpha: 1)
    }
    
    class func fontGray() -> UIColor {
        return UIColor.gray
    }
    
    class func cyanGreen() -> UIColor {
        
        return UIColor.setRGB(0x56C350)
    }
    
    class func signBgColor() -> UIColor {
        return UIColor.setRGB(0x99dfdbdb)
    }
    
    class func mineColor() -> UIColor {
        return setRGB(0xf0f0f0)
    }
    
    class func verifyColor() -> UIColor {
        return setRGB(0xdddddd)
    }
    
    class func editColor() -> UIColor {
        return setRGB(0xf2f2f2)
    }
    
    class func marqueeColor() -> UIColor {
        return setRGB(0xfae8ca)
    }
    
    class func moveColor() -> UIColor {
        return setRGB(0xF69796)
    }
    
    class func recordYellow() -> UIColor {
        return setRGB(0xf2ba1e)
    }
    
    class func recordBlue() -> UIColor {
        return setRGB(0x1fa7b2)
    }
    
    class func recordGreen() -> UIColor {
        return setRGB(0x99ae20)
    }
    
    class func recordRed() -> UIColor {
        return setRGB(0xe96128)
    }
    
    class func startBlue() -> UIColor {
        return setRGB(0x00EEFF)
    }
    
    class func centerColor() -> UIColor {
        return setRGB(0x00B2FF)
    }
    
    class func endColor() -> UIColor {
        return setRGB(0x0088FF)
    }
    
    class func phoneColor() -> UIColor {
        return setRGB(0x6699cc)
    }
    
    class func titleColor() -> UIColor {
        return setRGB(0xE1E2F8)
    }
    
    // MARK: 十六进制转rgb
    class func setRGB(_ rgbValue:UInt) -> UIColor {
        return UIColor.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: 1)
    }
}

// MARK: - UIImageView
extension UIImageView {
    public func setUrlImage(with urlStr:String? ,placeholder: UIImage?){
        
        self.sd_setImage(with: URL.init(string: urlStr ?? ""), placeholderImage: placeholder)
    }
}

extension UIImage {
    
    //MARK: 颜色转图片
    class func imageWithColor( _ color:UIColor) -> UIImage {
        
        let rect = CGRect.init(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
        
    }
    
    //MARK: 加载webp图片
    class func imageWithName( _ imageName:String) -> UIImage {
        
        let path = Bundle.main.path(forResource: imageName, ofType: "webp")
        let data = NSData.init(contentsOfFile: path ?? "")
        
        return UIImage.sd_image(with: data! as Data)!
    }
}

//MARK: String
extension String {
    
    /**
     获取文本范围
     */
    public func size(font : CGFloat ,  width:CGFloat) -> CGSize{
        let size = NSString.init(string: self).boundingRect(with: .init(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: font)], context: nil).size
        return CGSize.init(width: size.width + 10, height: size.height + 10)
    }
    
    public func size(font : CGFloat ,  height :CGFloat) -> CGSize{
        let size = NSString.init(string: self).boundingRect(with: .init(width: CGFloat.greatestFiniteMagnitude, height: height), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: font)], context: nil).size
        return CGSize.init(width: size.width + 10, height: size.height + 10)
    }
    
    //MARK: 时间戳转时间
    public func getDate() -> String {
        
        let date = Date.init(timeIntervalSince1970: Double(self)!)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateString = formatter.string(from: date)
        
        return dateString
    }
    
    //MARK: 时间转时间戳
    public func getTimestamp() -> Double {

        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd"
        
        let last = formatter.date(from: self)
        let timeStamp = last?.timeIntervalSince1970
    
        return timeStamp!
    }
    
    //MARK: 还款日期
    public func distanceRepaymentDate() -> String {
        
        let time = (self.getTimestamp()) - KMTool.getCurrentTime().getTimestamp()
        
        let day = Int(time/(24*60*60))
        var repaymentText = ""
        
        if day > 0 {
            if day > 365 {
                repaymentText = "1年以上"
            }else{
                repaymentText = "还有\(day)天"
            }
            
        }else if day == 0 {
            repaymentText = "今天到期"
        }else{
            if day < -365 {
                repaymentText = "已逾期1年以上"
            }else{
                repaymentText = "已逾期\(-day)天"
            }
            
        }
        
        return repaymentText
    }
    
    //MARK: 字体颜色
    public func setTextColor(color:UIColor,ranStr:String) -> NSAttributedString {
        
        let str = NSMutableAttributedString.init(string: self)
        let range = (self as NSString).range(of: ranStr)
        str.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        return str
    }
    
    //MARK: 字体大小
    public func setTextFont(color:UIColor?=UIColor.black,fontSize:CGFloat,ranStr:String) -> NSAttributedString {
        
        let str = NSMutableAttributedString.init(string: self)
        let range = (self as NSString).range(of: ranStr)
        str.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: RATIO(maxNum: fontSize)), range: range)
        str.addAttribute(NSAttributedStringKey.foregroundColor, value: color!, range: range)
        return str
    }
}

extension Notification.Name {
    
    /// 资讯推送
    static public let informationPush = Notification.Name(rawValue: information_title)
    
    /// 服务推送
    static public let servicePush = Notification.Name(rawValue: service_title)
    
    /// 理财推送
    static public let fiscalPush = Notification.Name(rawValue: fiscal_title)
    
    /// 贷款推送
    static public let loanPush = Notification.Name(rawValue: loan_title)
    
    ///提额推送
    static public let amountRaisedPush = Notification.Name(rawValue: "amountRaisedPush")
    
    ///热门羊毛推送
    static public let popularWoolPush = Notification.Name(rawValue: "popularWool")
    
    /// 添加账单
    static public let addBillPush = Notification.Name(rawValue: "addBillPush")
    
    ///联系银行
    static public let contactTheBank = Notification.Name(rawValue: "contactBank")
    
    ///热门银行
    static public let popularBankPush = Notification.Name(rawValue: "popularBank")
    
}

extension UITextField {
    
    convenience init(Width:CGFloat) {
        self.init()
        
        //设置左边视图的宽度
        self.leftView = UIView.init(frame: .init(x: 0, y: 0, width: Width, height: 0))
        
        self.rightView = UIView.init(frame: .init(x: 0, y: 0, width: Width, height: 0))
        //设置显示模式为永远显示(默认不显示 必须设置 否则没有效果)
        
        self.leftViewMode = .always
        self.rightViewMode = .always
    }
}












